function avg_file( idlPath, idlFile, strPath, strFile )
%--------------------------------------------------------------------------
% Average Spectrum of Audio Files
%
% Cooper Baker - 2014
%--------------------------------------------------------------------------

close all;

% Settings
%--------------------------------------------------------------------------
winSize = 512;
overlap = 4;
win     = chebwin( winSize, 125 );
name    = 'Average Spectrum';

% Initializations
%--------------------------------------------------------------------------
if any( exist( 'idlFile' ) ~= 1 )
    [ idlFile, idlPath ] = uigetfile( '*.wav', 'Ideal Audio File' );
    [ strFile, strPath ] = uigetfile( '*.wav', 'Stretched Audio File' );
end

[ idlBuf, sr ] = audioread( [ idlPath, idlFile ] );
[ strBuf, sr ] = audioread( [ strPath, strFile ] );
halfWinSize    = winSize / 2;
idlSize        = length( idlBuf );
strSize        = length( strBuf );
idlMsec        = ( idlSize / sr ) * 1000;
gridMsec       = 500;
gridHops       = gridMsec / ( ( ( winSize / overlap ) / sr ) * 1000 );
hopSize        = winSize / overlap;
hopMsec        = ( hopSize / sr ) * 1000;
idlAvg         = zeros( halfWinSize, 1 );
strAvg         = zeros( halfWinSize, 1 );
idlIndex       = 1;
strIndex       = 1;
winSum         = sum( win );

% Normalization
%--------------------------------------------------------------------------

% get file metadata
idlInfo = audioinfo( [ idlPath, idlFile ] );
strInfo = audioinfo( [ strPath, strFile ] );

% get file normalization coefficient
idlFileNorm = str2num( idlInfo.Title );
strFileNorm = str2num( strInfo.Title );

% de-normalize normalized .wav file data
idlRaw = idlBuf / idlFileNorm;
strRaw = strBuf / strFileNorm;

% make hann windows
idlWin = hann( idlSize );
strWin = hann( strSize );

% window the files
idlNormWin = idlRaw .* idlWin;
strNormWin = strRaw .* strWin;

% calculate rms of windowed files
idlRms = rms( idlNormWin );
strRms = rms( strNormWin );

% calculate normalization scalar
strScale = 1 / ( strRms / idlRms );

% normalize stretch buffer to match ideal buffer
idlNorm = idlRaw;
strNorm = strRaw * strScale;

% Analysis Loops
%--------------------------------------------------------------------------

% ideal file
hop = 1;
hopMax = length( idlNorm ) - winSize;
while hop < hopMax

    % copy analysis frame from buffer
    idlFrame = idlNorm( hop : hop + winSize - 1 );

    % window the frame
    idlWin = idlFrame .* win;

    % perform fft
    idlFullSpec = fft( idlWin );

    % save relevant half of spectrum
    idlSpec = idlFullSpec( 1 : halfWinSize );

    % calculate magnitude spectrum
    idlMag = abs( idlSpec );

    % store all magnitude spectra into array
    idlArray( idlIndex, : ) = idlMag;

    % increment indices
    hop = hop + hopSize;
    idlIndex = idlIndex + 1;
end

% stretched file
hop = 1;
hopMax = length( strNorm ) - winSize;
while hop < hopMax

    % copy analysis frame from buffer
    strFrame = strNorm( hop : hop + winSize - 1 );

    % window the frame
    strWin = strFrame .* win;

    % perform fft
    strFullSpec = fft( strWin );

    % save relevant half of spectrum
    strSpec = strFullSpec( 1 : halfWinSize );

    % calculate magnitude spectrum
    strMag = abs( strSpec );

    % store all magnitude spectra into array
    strArray( strIndex, : ) = strMag;

    % increment indices
    hop = hop + hopSize;
    strIndex = strIndex + 1;
end

% calculate average spectra from all hops
idlMag = sum( idlArray ) / idlIndex;
strMag = sum( strArray ) / strIndex;

% calculate amplitude spectra
idlAmp = ( idlMag / winSum );
strAmp = ( strMag / winSum );

% calculate sones spectra
idlSones = idlAmp .^ 0.6;
strSones = strAmp .^ 0.6;

% calculate decibel spectra
idlDb  = 20 * log10( idlAmp );
strDb  = 20 * log10( strAmp );

% copy spectra to plot arrays
idlPlot = idlSones;
strPlot = strSones;

% calculate ideal plot offset
offset = 0;
offset = abs( min( [ min( idlPlot ) min( strPlot ) ] ) );

% offset plots
idlPlot = idlPlot + offset;
strPlot = strPlot + offset;

% calculate absolute difference between plots (error)
difPlot = abs( idlPlot - strPlot );

% calculate mean error value
difMean = sum( difPlot ) / ( halfWinSize );

% calculate max error value
difMax = max( difPlot );

% Plot
%--------------------------------------------------------------------------
fontName   = 'Times New Roman';
fontSize   = 12;
xSpc       = 0.103;
ySpc       = 0.64;

fig = figure( 1 );
set( fig, 'Name', name );
set( fig, 'Position', [ 0 0 800 275 ] );
set( fig, 'defaultAxesFontName', fontName );
set( fig, 'defaultTextFontName', fontName );

% spectra
plot( idlPlot, 'Color', [ 0.2 0.2 0.8 ], 'LineWidth', 6 );
hold on;
plot( strPlot, 'Color', [ 0.2 0.8 0.2 ], 'LineWidth', 2 );
hold on;
plot( difPlot, 'Color', [ 0.8 0.2 0.2 ], 'LineWidth', 3 );
hold on;

% grid and labels
grid on;
yMin = min( [ min( idlPlot ) min( strPlot ) min( difPlot ) ] );
yMax = max( [ max( idlPlot ) max( strPlot ) max( difPlot ) ] );
axis( [ 0 halfWinSize yMin yMax ]);
set( gca, 'XTick', [ 0 : ( halfWinSize / ( sr / 4000 ) ) : halfWinSize ] );
set( gca, 'XTickLabel', [ 0 : 2000 : ( sr / 2 ) ] );
xlabel( 'Frequency' );
ylabel( 'Sones' );
% title( name, 'FontSize', fontSize );

% legend
xPos = ( halfWinSize + halfWinSize * -xSpc );
yPos = yMax * ySpc;
leg = legend( 'Ideal', 'Stretch', 'Error' );
set( leg, 'Location', 'NorthEast' );
maxStr = sprintf( ' Max: %2.5f', difMax );
meanStr = sprintf( ' Avg: %2.5f', difMean );
legStr = sprintf( '  Sones Error\n%s\n%s', maxStr, meanStr );
text( xPos, yPos, legStr, 'BackgroundColor', 'w', 'EdgeColor', 'k' );

% tighen up figure borders
tightfig();

% Save Data to Files
%--------------------------------------------------------------------------

% get file name
[ a, fileName, b ] = fileparts( strFile );

% write plot to file
hgexport( fig, [ fileName, '.avg.eps' ] );

% write error data to files
csvFile = sprintf( '%s.avg.err.csv', fileName );
csvwrite( csvFile, difPlot );

% EOF
